<template>
  <div class="admin-elder">
    <div class="header">
      <h2>老人管理</h2>
      <el-button type="primary" @click="handleAdd">新增老人</el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="老人姓名">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入老人姓名"
              clearable
              style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="健康状况">
          <el-select
              v-model="queryParams.healthStatus"
              placeholder="请选择健康状况"
              clearable
              style="width: 200px"
          >
            <el-option label="良好" value="良好" />
            <el-option label="一般" value="一般" />
            <el-option label="较差" value="较差" />
            <el-option label="需要特别关注" value="需要特别关注" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责护工">
          <el-select
              v-model="queryParams.caregiverId"
              placeholder="请选择负责护工"
              clearable
              style="width: 200px"
          >
            <el-option
                v-for="caregiver in caregivers"
                :key="caregiver.caregiverId"
                :label="caregiver.name"
                :value="caregiver.caregiverId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="elderList"
        v-loading="tableLoading"
        style="width: 100%"
        border
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="elderId" label="老人ID" width="100" align="center" />
      <el-table-column prop="name" label="老人姓名" width="120" align="center" />
      <el-table-column prop="age" label="年龄" width="80" align="center" />
      <el-table-column prop="gender" label="性别" width="80" align="center">
        <template #default="{ row }">
          {{ row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="healthStatus" label="健康状况" width="120" align="center" />
      <el-table-column prop="phone" label="联系电话" width="130" align="center" />
      <el-table-column prop="bedId" label="床位号" width="100" align="center" />
      <el-table-column prop="elderSector" label="区域" width="100" align="center" />
      <el-table-column prop="caregiverName" label="负责护工" width="120" align="center" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="warning" size="small" @click="handleStatus(row)">
            {{ row.status === 'active' ? '设为失效' : '设为有效' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="600px"
        :before-close="handleClose"
    >
      <el-form
          ref="elderFormRef"
          :model="elderForm"
          :rules="elderRules"
          label-width="100px"
      >
        <el-form-item label="老人姓名" prop="name">
          <el-input v-model="elderForm.name" placeholder="请输入老人姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number
              v-model="elderForm.age"
              :min="60"
              :max="120"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="elderForm.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="健康状况" prop="healthStatus">
          <el-select v-model="elderForm.healthStatus" placeholder="请选择健康状况" style="width: 100%">
            <el-option label="良好" value="良好" />
            <el-option label="一般" value="一般" />
            <el-option label="较差" value="较差" />
            <el-option label="需要特别关注" value="需要特别关注" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="elderForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="elderForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="床位号" prop="bedId">
          <el-select v-model="elderForm.bedId" placeholder="请选择床位" style="width: 100%">
            <el-option
                v-for="bed in availableBeds"
                :key="bed.bedId"
                :label="`${bed.bedId} (${bed.roomId})`"
                :value="bed.bedId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区域" prop="elderSector">
          <el-input v-model="elderForm.elderSector" placeholder="请输入区域" />
        </el-form-item>
        <el-form-item label="证件类型" prop="elderIdType">
          <el-select v-model="elderForm.elderIdType" placeholder="请选择证件类型" style="width: 100%">
            <el-option label="身份证" value="身份证" />
            <el-option label="护照" value="护照" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责护工" prop="caregiverId">
          <el-select v-model="elderForm.caregiverId" placeholder="请选择负责护工" style="width: 100%">
            <el-option
                v-for="caregiver in caregivers"
                :key="caregiver.caregiverId"
                :label="caregiver.name"
                :value="caregiver.caregiverId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { elderApi } from '@/api/elder'
import { caregiverApi } from '@/api/caregiver'
import { bedApi } from '@/api/bed'

// 响应式数据
const tableLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const elderList = ref([])
const caregivers = ref([])
const availableBeds = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  healthStatus: '',
  caregiverId: ''
})
const elderForm = reactive({
  elderId: '',
  name: '',
  age: 60,
  gender: '1',
  healthStatus: '',
  phone: '',
  address: '',
  bedId: '',
  elderSector: '',
  elderIdType: '身份证',
  caregiverId: ''
})
const elderRules = {
  name: [{ required: true, message: '请输入老人姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  healthStatus: [{ required: true, message: '请选择健康状况', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  bedId: [{ required: true, message: '请选择床位', trigger: 'change' }],
  caregiverId: [{ required: true, message: '请选择负责护工', trigger: 'change' }]
}
const elderFormRef = ref()

// 状态映射
const getStatusType = (status) => {
  const statusMap = { active: 'success', inactive: 'info', outing: 'warning' }
  return statusMap[status] || 'info'
}
const getStatusText = (status) => {
  const statusTextMap = { active: '在院', inactive: '失效', outing: '外出' }
  return statusTextMap[status] || status
}

// 加载老人列表
const loadElders = async () => {
  tableLoading.value = true
  try {
    const response = await elderApi.getElders(queryParams)
    elderList.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载老人列表失败')
    console.error('加载老人列表失败:', error)
  } finally {
    tableLoading.value = false
  }
}

// 加载护工列表
const loadCaregivers = async () => {
  try {
    const response = await caregiverApi.getCaregivers({ pageNum: 1, pageSize: 100 })
    caregivers.value = response.data.records || []
  } catch (error) {
    console.error('加载护工列表失败:', error)
    ElMessage.error('加载护工列表失败，请检查接口地址')
  }
}

// 加载可用床位
const loadAvailableBeds = async () => {
  try {
    const response = await bedApi.getAvailableBeds()
    availableBeds.value = response.data || []
  } catch (error) {
    console.error('加载可用床位失败:', error)
    ElMessage.error('加载可用床位失败')
  }
}

// 搜索/重置/分页
const handleSearch = () => { queryParams.pageNum = 1; loadElders() }
const handleReset = () => {
  Object.assign(queryParams, { pageNum: 1, pageSize: 10, name: '', healthStatus: '', caregiverId: '' })
  loadElders()
}
const handleSizeChange = (val) => { queryParams.pageSize = val; queryParams.pageNum = 1; loadElders() }
const handleCurrentChange = (val) => { queryParams.pageNum = val; loadElders() }

// 新增/编辑/状态切换
const handleAdd = () => {
  dialogTitle.value = '新增老人'
  Object.assign(elderForm, { elderId: '', name: '', age: 60, gender: '1', healthStatus: '', phone: '', address: '', bedId: '', elderSector: '', elderIdType: '身份证', caregiverId: '' })
  dialogVisible.value = true
}
const handleEdit = (row) => {
  dialogTitle.value = '编辑老人信息'
  Object.assign(elderForm, { ...row, gender: row.gender.toString() })
  dialogVisible.value = true
}
const handleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要${row.status === 'active' ? '设为失效' : '设为有效'}吗？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
    await elderApi.updateElderStatus(row.elderId, row.status === 'active' ? 'inactive' : 'active')
    ElMessage.success('操作成功')
    loadElders()
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('操作失败')
  }
}
const handleClose = () => { dialogVisible.value = false; elderFormRef.value?.resetFields() }
const handleSubmit = async () => {
  if (!elderFormRef.value) return
  try {
    await elderFormRef.value.validate()
    if (dialogTitle.value === '新增老人') {
      await elderApi.addElder(elderForm)
      ElMessage.success('新增成功')
    } else {
      await elderApi.updateElder(elderForm)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadElders()
  } catch (error) {
    ElMessage.error(error.errors ? '请完善表单信息' : '操作失败')
  }
}

// 初始化
onMounted(() => {
  loadElders()
  loadCaregivers()
  loadAvailableBeds()
})
</script>

<style scoped>
.admin-elder { padding: 20px; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.filter-container { background: #f8f9fa; padding: 20px; border-radius: 4px; margin-bottom: 20px; }
.pagination-container { margin-top: 20px; text-align: right; }
</style>